package com.zbhk.qc.service.impl;

import com.zbhk.qc.configuration.security.SecurityConfiguration;
import com.zbhk.qc.dto.BaseResponseEntity;
import com.zbhk.qc.dto.BgLoginOutput;
import com.zbhk.qc.dto.LoginInput;
import com.zbhk.qc.dto.VdAdClickVO;
import com.zbhk.qc.entity.BgUser;
import com.zbhk.qc.entity.VdAdClick;
import com.zbhk.qc.entity.VdPublicArticle;
import com.zbhk.qc.mapper.BgUserMapper;
import com.zbhk.qc.mapper.VdAdClickMapper;
import com.zbhk.qc.mapper.VdPublicArticleMapper;
import com.zbhk.qc.service.VdAdClickService;
import com.zbhk.qc.util.MD5Util;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Lazy(false)
@Service
@Slf4j
public class VdAdClickServiceImpl implements VdAdClickService {

    @Autowired
    private VdAdClickMapper vdAdClickMapper;

    @Autowired
    private VdPublicArticleMapper vdPublicArticleMapper;

    @Override
    public BaseResponseEntity<VdAdClickVO> getAdUrl(Long paId, Long userId) {

        BaseResponseEntity<VdAdClickVO> responseEntity = new BaseResponseEntity();
        VdAdClickVO vdAdClickVO = new VdAdClickVO();

        VdPublicArticle vdPublicArticle = vdPublicArticleMapper.selectById(paId);
        if (vdPublicArticle == null) {
            responseEntity.setSuccess(false);
            responseEntity.setErrorMessage("该文章不存在！");
            return responseEntity;
        }

        Map<String,Object> map = new HashMap<>();
        map.put("pa_id", paId);
        map.put("user_id", userId);
        List<VdAdClick> vdAdClickList = vdAdClickMapper.selectByMap(map);
        if (vdAdClickList == null || vdAdClickList.size() == 0) {
            VdAdClick vdAdClick = new VdAdClick();
            vdAdClick.setPaId(paId);
            vdAdClick.setUserId(userId);
            String code = this.getInviteCode(paId, userId);
            vdAdClick.setInviteCode(code);
            vdAdClick.setQrCodeUrl(vdPublicArticle.getUrlname() + "?uuid=" + code);
            vdAdClickMapper.insert(vdAdClick);
        }
        List<VdAdClick> list = vdAdClickMapper.selectByMap(map);
        vdAdClickVO.setQrCodeUrl(list.get(0).getQrCodeUrl());
        responseEntity.setData(vdAdClickVO);
        return responseEntity;
    }

    private String getInviteCode(Long paId, Long userId){
        String uuid = UUID.randomUUID().toString();
        return uuid + "_" + String.valueOf(paId) + "_" + String.valueOf(userId);
    }
}

  